package server

import (
	stdCtx "context"
	"github.com/kataras/iris/v12"
	"github.com/urfave/cli/v2"
	"gitlab-dingtalk/server/config"
	"gitlab-dingtalk/server/config/db"
	"gitlab-dingtalk/server/config/logger"
	"sync"
	"time"
)

var Web = cli.Command{
	Name:   "web",
	Usage:  "启动运行监听服务",
	Action: runWeb,
	Flags:  initFlag(),
}

func runWeb(c *cli.Context) error {
	config := config.Configuration{
		FilePath:   c.String("config.path"),
		CliContext: c,
	}
	appConfig := config.GetApplicationConfig()
	logger.InitLogger(appConfig.LoggerConfig)
	app := iris.New()
	serverWG := new(sync.WaitGroup)
	defer serverWG.Wait()
	iris.RegisterOnInterrupt(func() {
		serverWG.Add(1)
		defer serverWG.Done()
		ctx, cancel := stdCtx.WithTimeout(stdCtx.Background(), 20*time.Second)
		defer cancel()
		//关闭数据库链接
		db.CloseDB()
		// 关闭全部主机
		app.Shutdown(ctx)
	})
	if eer := db.InitDb(appConfig.Datasource); eer != nil {
		return eer
	}
	InitRouter(app)
	return app.Listen(appConfig.Server.HostPort)
}

func initFlag() []cli.Flag {
	flag := []cli.Flag{
		&cli.StringFlag{
			Name:    "winjoin",
			Aliases: []string{"wj"},
			Usage:   "启动文景 链接数据库",
		},
		&cli.StringFlag{
			Name:    "config.path",
			Aliases: []string{"cp"},
			Usage:   "配置初始化文件路径",
			Value:   "./application.yml",
		},
		&cli.StringFlag{
			Name:  "hostPort",
			Usage: "需要监听的端口",
			Value: ":8080",
		},
	}
	return flag
}
